package ma.co.cdm.esign.workers;

import java.io.File;
import java.util.Calendar;
import java.util.TimeZone;

import ma.co.cdm.esign.vo.MySisSolrDoc;
import ma.co.cdm.esign.vo.SolrBean;

public class ArchiveProcessing {

	public void archiveFile(SolrBean solrbean, String destFolder) throws Exception {
		if(solrbean == null || destFolder == null)
		{
			return;
		}
		
		if(solrbean instanceof MySisSolrDoc)
		{
			MySisSolrDoc bean = (MySisSolrDoc)solrbean;
			File destFolderFile = new File(destFolder);
			if(!destFolderFile.exists())
			{
				destFolderFile.mkdirs();
			}
			File fileToArchive = new File(bean.getPathFsXml());
			String suffixDate = getSuffixDatePath();
			File folderDest = new File(destFolderFile.getAbsolutePath()+File.separator+suffixDate);
			if(!folderDest.exists())
			{
				folderDest.mkdirs();
			}
			
			File newFile =new File(folderDest.getAbsolutePath()+File.separator+fileToArchive.getName());
			if(fileToArchive.renameTo(newFile)){
				bean.setPathFsXml(newFile.getAbsolutePath());
				bean.setDocid(suffixDate+"_"+fileToArchive.getName());
    	   }else{
    		   throw new Exception("Impossible d'archiver le fichier "+ fileToArchive.getAbsolutePath());
    	   }
		}		
	}
	
	public String getSuffixDatePath()
	{
		Calendar localCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));	     
        int currentDay = localCalendar.get(Calendar.DATE);
        int currentMonth = localCalendar.get(Calendar.MONTH) + 1;
        int currentYear = localCalendar.get(Calendar.YEAR);  
        int currentHour = localCalendar.get(Calendar.HOUR_OF_DAY);  
        int currentMinute = localCalendar.get(Calendar.MINUTE);  
        int currentSeconde = localCalendar.get(Calendar.SECOND);  
        String suffixDatePath = currentYear+File.separator+currentMonth+File.separator+currentDay+File.separator+currentHour+File.separator+currentMinute+File.separator+currentSeconde;
        return suffixDatePath;
	}

}
